
  public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
  class Solution {
      public ListNode swapNodes(ListNode head, int k) {
          if(head == null || head.next ==null ){
              return head;
          }

          int size = 0;
          ListNode cur = head;
          while(cur != null){
              cur = cur.next;
              size++;
          }

          ListNode slow = head;
          ListNode fast = head;
          ListNode fastPrev = head;
          ListNode slowPrev = head;
          ListNode curNext = head.next;
          if(k == 1  || k == size){
              if(head.next.next == null){
                  curNext.next = head;
                  head.next = null;
                  return curNext;
              }else{
                  int count = size - 2;
                  while(count > 0 ){
                      fastPrev = fastPrev.next;
                      count--;
                  }
                  fast = fastPrev.next;
                  fast.next = slow.next;
                  fastPrev.next = slow;
                  slow.next = null;
                  return fast;
              }
          }
          else{
              cur = head;
              int count1 = size - k - 1;//2
              while(count1 >0){
                  fastPrev = fastPrev.next;
                  count1--;
              }
              int count2 = k-1;//2
              while(count2 > 0){
                  slowPrev = cur;
                  cur = cur.next;
                  count2--;
              }
              fast = fastPrev.next;
              slow = slowPrev.next;
          }
          ListNode last1 = fast.next;
          ListNode last2 = slow.next;
          if(size % 2 == 0 && size / 2 == k ){
              slowPrev.next = fast;
              last2.next = slow;
              fastPrev.next = last1;
          }else if(size % 2 == 0 && size / 2 + 1 == k){
              fastPrev.next = last1;
              slow.next = fast;
              slowPrev.next = last2;
          }
          else{
              fast.next = last2;
              slow.next = last1;
              fastPrev.next = slow;
              slowPrev.next = fast;
          }
          return head;
      }
  }
